package org.crh.appointment;

import lombok.extern.slf4j.Slf4j;
import org.crh.common.mapper.ScheduleMapper;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: RenHai Chen
 * @date: 2025/3/31 10:44
 */
@Configuration
@EnableScheduling
@Slf4j
public class StockConsistencyTask {
    @Resource
    private ScheduleMapper scheduleMapper;

    @Autowired
    private RedissonClient redissonClient;


//    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkStockConsistency() {
        // 获取所有科室ID
        List<Long> scheduleIds = scheduleMapper.getAllIds();
        scheduleIds.forEach(id -> {
            String key =String.valueOf(id);
            RBucket<String> bucket = redissonClient.getBucket(key);
            Integer redisStock = Integer.valueOf(bucket.get());
            Integer dbStock = scheduleMapper.selectStock(id);
            if (redisStock != dbStock) {
                log.warn("库存不一致 scheduleId:{}, Redis:{}, DB:{}", id, redisStock, dbStock);
                // 以数据库为准修正
                bucket.set(dbStock.toString());
            }
        });
    }
}
